package com.ysxsoft.wdg.ui.activity.center_st;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.bean.st.CompanyBean;
import com.ysxsoft.wdg.bean.st.CompanyDetailBean;
import com.ysxsoft.wdg.constant.MCConfig;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.functions.Consumer;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.LOCATION_UP;

/**
 * 商家详情
 */
public class StShopDetail3Activity extends BaseActivity {

    public static void start(Context context, CompanyDetailBean companyBean) {
        Intent intent = new Intent(context, StShopDetail3Activity.class);
        intent.putExtra("detail", companyBean);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_fen)
    TextView tvShopFen;
    @BindView(R.id.tv_shop_type)
    TextView tvShopType;
    @BindView(R.id.tv_shop_phone)
    TextView tvShopPhone;
    @BindView(R.id.tv_shop_location)
    TextView tvShopLocation;
    @BindView(R.id.photos)
    BGANinePhotoLayout ninePhotoLayout;

    private String phone = "";
    private CompanyDetailBean companyBean;
    private double lat, lng;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_detail3;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("商家详情");

        Intent intent = getIntent();
        companyBean = intent.getParcelableExtra("detail");
        companyBean.getCompanyid();
        if (companyBean != null) {

            ViewUtils.loadRoundCircleImage(this, companyBean.getPic(), ivShopLogo);
            tvShopName.setText(companyBean.getName());
            tvShopFen.setText("评分" + companyBean.getGrade() + "  月销" + companyBean.getSold());
            tvShopType.setText(companyBean.getCategoryid());

            phone = companyBean.getPhone();
            tvShopPhone.setText(phone);
            tvShopLocation.setText(companyBean.getMap_address());
            lat = companyBean.getLat();
            lng = companyBean.getLng();
//            ViewUtils.loadImage(this, companyBean.getQualification().get(0), ivYyzz);

            ninePhotoLayout.setData((ArrayList<String>) companyBean.getQualification());
            ninePhotoLayout.setDelegate(new BGANinePhotoLayout.Delegate() {
                @Override
                public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                    File downloadDir = new File(MCConfig.PICTURE_DIR);
                    BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(mContext)
                            .saveImgDir(downloadDir); // 保存图片的目录，如果传 null，则没有保存图片功能
                    photoPreviewIntentBuilder
                            .previewPhotos((ArrayList<String>) models).currentPosition(position); // 当前预览图片的索引
                    mContext.startActivity(photoPreviewIntentBuilder.build());
                }
            });
        }
        initLocation();
    }

    @Override
    protected void setListener() {

    }


    @OnClick({R.id.title_finish, R.id.tv_shop_phone, R.id.tv_shop_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv_shop_phone:
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showToast("请稍后再试");
                    return;
                }
                AlertViewFactory.getInstance().getCallAlert(mContext, phone).show();
                break;
            case R.id.tv_shop_location:
                if (slat == 0.0 || slng == 0) {
                    ToastUtils.showToast("正在获取您的位置，请稍后再试!");
                    return;
                }
                if(isInstalled(this,"com.autonavi.minimap")){
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setData(Uri.parse("amapuri://route/plan/?sid=BGVIS1&slat=" + SharePrefUtils.getLatitude() + "&slon=" + SharePrefUtils.getLongitude() + "&sname=我的位置&did=BGVIS2&dlat=" + companyBean.getLat() + "&dlon=" + companyBean.getLng() + "&dname=" + companyBean.getName() + "&dev=0&t=0"));
                    startActivity(intent);
                }else{
                    ToastUtils.showToast("请安装高德地图！");
                }
                break;
        }
    }

    private double slat = 0.0, slng = 0.0;

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);


        new RxPermissions(this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        //启动定位
                        mLocationClient.startLocation();
                    }
                });
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    EventBus.getDefault().post(new CommentEvent(LOCATION_UP));
                    String address = amapLocation.getCity().replace("市", "");
//                    handler.sendEmptyMessageDelayed(0, 2000);
                    //可在其中解析amapLocation获取相应内容。
                    SharePrefUtils.saveLatitude(amapLocation.getLatitude() + "");
                    SharePrefUtils.saveLongitude(amapLocation.getLongitude() + "");
                    SharePrefUtils.saveAddress(address);
                    slng = amapLocation.getLongitude();
                    slat = amapLocation.getLatitude();

                    KLog.e("Latitude=" + amapLocation.getLatitude() + ",Longitude=" + amapLocation.getLongitude());
                } else {
//                    address = "定位失败";
//                    handler.sendEmptyMessageDelayed(0, 2000);
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    KLog.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    /**
     * 应用是否安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstalled(Context context, String packageName) {
        boolean installed = false;
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        List<ApplicationInfo> installedApplications = context.getPackageManager().getInstalledApplications(0);
        for (ApplicationInfo in : installedApplications) {
            if (packageName.equals(in.packageName)) {
                installed = true;
                break;
            } else {
                installed = false;
            }
        }
        ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos=activityManager.getRunningAppProcesses();
        for (int i = 0; i <runningAppProcessInfos.size() ; i++) {
            ActivityManager.RunningAppProcessInfo info=runningAppProcessInfos.get(i);
        }
        return installed;
    }

}
